# -*- coding: utf-8 -*-
# @Author : Yuan
from apps.users.models import User
from rest_framework import serializers
from apps.goods.models import SKUImage, SKU, GoodsCategory, SPU
from apps.goods.models import SPUSpecification, SpecificationOption, SKUSpecification
from django.db import transaction


class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'password']
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
        }

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)


class SKUImageModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = '__all__'

    def update(self, instance, validated_data):
        image_data = validated_data.get('image')
        sku_id = validated_data.get('sku')
        from fdfs_client.client import Fdfs_client
        f_client = Fdfs_client('utils/fastdfs/client.conf')
        res = f_client.upload_by_buffer(image_data.read())
        # res = f_client.modify_by_buffer(image_data.read(), instance.image.name)
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError("上传失败")
        # 保存数据
        image_url = res['Remote file_id']
        instance.sku_id = sku_id
        instance.image = image_url
        instance.save()
        return instance


class SKUSpecificationModelSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUModelSerializer(serializers.ModelSerializer):
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    specs = SKUSpecificationModelSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        specs = validated_data.pop('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, **spec)
            except Exception as e:
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)
            return sku

    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                instance = super().update(instance, validated_data)
                for spec in specs:
                    SKUSpecification.objects.filter(sku=instance, spec_id=spec['spec_id']).update(option_id=spec['option_id'])
            except Exception as e:
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)
        return instance


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class SPUModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SPU
        fields = ['id', 'name']


class SpecificationOptionModerSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpecificationOption
        fields = ['id', 'value']


class SPUSpecificationModelSerializer(serializers.ModelSerializer):
    options = SpecificationOptionModerSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = ['id', 'name', 'options']





